package nio.socket;

import nio.bytebuffer.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false); // 非阻塞
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            // System.out.println("connecting...");
            SocketChannel sc = ssc.accept(); // 阻塞方法
            if (sc != null) {
                System.out.println("connected...{" + sc + "}");
                channels.add(sc);
            }
            for (SocketChannel channel : channels) {
                //    System.out.println("before read...{" + channel + "}");
                int read = channel.read(buffer); // 阻塞方法
                if (read > 0) {
                    buffer.flip();
                    ByteBufferUtil.debugRead(buffer);
                    buffer.clear();
                    System.out.println("after read...{" + channel + "}");
                }

            }
        }
    }
}

